import React, { useState, useEffect, useCallback } from 'react'
import { Tree, Input, message, Spin } from 'antd'
import _, { debounce, set } from 'lodash'
import { useSelector } from 'react-redux'
import { SearchOutlined } from '@ant-design/icons'
import { Card } from '&/appComponents/Antd'
import { getEnterpriseData } from '&/api/electricity'
import './index.scss'

const List = (props) => {
  const { tap, setTap } = props
  const record = useSelector((state) => state.getRecordReducer)
  const values = JSON.parse(localStorage.getItem('user'))
  const { DirectoryTree } = Tree
  const [treeDataList, setTreeDataList] = useState([])
  const [expandedKeys, setExpandedKeys] = useState(['0-0'])
  const [selectedKeys, setSelectedKeys] = useState(['0-0-0'])
  const [selectContent, setSelectContent] = useState()
  const [autoExpandParent] = useState(true)
  const [loading, setLoading] = useState(false)
  //搜索功能
  const onChange = (e) => {
    if (treeDataList.length > 0) {
      if (e.target.value != '') {
        debounceSearch(e.target.value)
      } else {
        setSelectedKeys([treeDataList?.[0].children[0].key])
        setExpandedKeys([treeDataList?.[0].children[0].parentKey])
        tap === '1'
          ? getEntData('', 'entAreaData', tap)
          : getEntData('', 'entIndustryData', tap)
      }
    }
  }
  //搜索防抖
  const debounceSearch = useCallback(
    _.debounce((value) => {
      tap === '1'
        ? getEntData(value, 'entAreaData', tap)
        : getEntData(value, 'entIndustryData', tap)
    }, 3000),
    []
  )
  //   区域选择
  const handleChange = (value) => {
    setTap(value)
  }
  useEffect(() => {
    setLoading(true)
    tap === '1'
      ? getEntData('', 'entAreaData', tap)
      : getEntData('', 'entIndustryData', tap)
  }, [tap])
  useEffect(() => {
    if (Object.keys(record).length > 0) {
      if (treeDataList.length > 0) {
        for (let index = 0; index < treeDataList.length; index++) {
          const item = treeDataList[index]
          const obj = item.children?.find((i) => {
            return i.title === record.company
          })
          if (obj) {
            setSelectedKeys([obj.key])
            setExpandedKeys([obj.parentKey])
            break
          }
        }
      }
    }
    // setLoading(false);
  }, [treeDataList, record.company])

  const getEntData = async (entName, localName, tap) => {
    const entDataList = localStorage.getItem(localName)
    let pretreeData 
    if (entDataList) {
      const res = JSON.parse(entDataList)
      pretreeData = generateTree(res)
    }
    const res = await getEnterpriseData({
      group_by: tap,
      ent_name: entName
    })
    if (entDataList !== JSON.stringify(res)) {
      const treedata = generateTree(res)
      updateTreeData(treedata)
      localStorage.setItem(localName, JSON.stringify(res))
      return
    }
    updateTreeData(pretreeData)
  }

  //生成树结构
  const generateTree = (res) => {
    const treeData = res?.data.map((item, index) => {
      return {
        title: tap === '1' ? item.county_name : item.industry_type,
        key: `0-${index}`,
        children: item.ent_info.map((t, i) => {
          return {
            title: t.ent_name,
            entId: t.ent_id,
            key: `0-${index}-${i}`,
            parentKey: `0-${index}`,
            isLeaf: true,
            icon:
              `0-${index}-${i}` == `0-0-0` ? (
                <div
                  style={{
                    width: '15px',
                    height: '15px',
                    borderRadius: '10pX',
                    backgroundColor: 'yellow',
                    lineHeight: '15px'
                  }}
                ></div>
              ) : (
                <div></div>
              )
          }
        })
      }
    })

    return treeData
  }

  //更新树形结构状态
  const updateTreeData = (treeData) => {
    setSelectContent([
      {
        entId: treeData[0] && treeData[0].children[0].entId,
        entName: treeData[0] && treeData[0].children[0].title
      }
    ])
    props.click([
      {
        entId: treeData[0] && treeData[0].children[0].entId,
        entName: treeData[0] && treeData[0].children[0].title
      }
    ])
    setSelectedKeys([treeData?.[0].children[0].key])
    setExpandedKeys([treeData?.[0].children[0].parentKey])
    setTreeDataList(treeData)
    setLoading(false)
  }
  // 树形组件选择
  const onSelect = (keys, info) => {
    if (!info.node.children) {
      let selectedContent = selectContent
      let treeSelect
      //对企业选中key的逻辑
      // selectedKeys.includes(keys[0]) && selectedKeys.length !== 1 //对应下一行的判断，是之前的代码，保证至少有一个
      if (selectedKeys.includes(keys[0]) && selectedKeys.length > 1) {
        const filterarr = selectedKeys.filter((item) => item !== keys[0])
        setSelectedKeys(filterarr)
        treeSelect = filterarr
      } else if (!selectedKeys.includes(keys[0]) && selectedKeys.length < 2) {
        setSelectedKeys([...selectedKeys, keys[0]])
        treeSelect = [...selectedKeys, keys[0]]
      } else if (!selectedKeys.includes(keys[0]) && selectedKeys.length == 2) {
        // 对选完两个后，重新选择时，将企业变空，重新进行添加key
        setSelectedKeys([])
        let selt = []
        // if (selt.includes(keys[0])) {
        //   const filterarr = selt.filter(item => item !== keys[0]);
        //   setSelectedKeys(filterarr)
        // } else
        if (!selt.includes(keys[0]) && selt.length < 2) {
          setSelectedKeys([...selt, keys[0]])
          treeSelect = [...selt, keys[0]]
        }
      } else {
        message.info('至少选择一项')
      }

      //调用主要选择的主企业，并添加图标
      IconMain(treeSelect, treeDataList)

      //对企业选中传值的逻辑
      // const notNull = selectedContent.some(obj => obj.hasOwnProperty('entId'))
      const notNull = selectedContent.some((item) => {
        return item.entId == info.node.entId
      })
      // notNull && selectedContent.length !== 1 //对应下一行的判断，是之前的代码，保证至少有一个
      if (notNull) {
        selectedContent = selectContent.filter(
          (item) => item.entId !== info.node.entId
        )
        const aa = new Set([...selectedContent])
        setSelectContent([...aa])
      } else if (selectedContent.length < 2 && !notNull) {
        selectedContent.push({
          entId: info.node.entId,
          entName: info.node.title
        })
        const aa = new Set([...selectedContent])
        setSelectContent([...aa])
      } else if (!notNull && selectedContent.length == 2) {
        // 对选完两个后，重新选择时，将企业传的值变空，重新进行添加企业id与企业名字
        setSelectContent([])
        const content = []
        const notNulls = content.some((item) => {
          return item.entId == info.node.entId
        })
        if (content.length < 2 && !notNulls) {
          content.push({
            entId: info.node.entId,
            entName: info.node.title
          })
          const aa = new Set([...content])
          setSelectContent([...aa])
        }
        // else if (notNulls) {
        //   let cintent = content.filter(item => item.entId !== info.node.entId);
        //   const aa = new Set([...cintent])
        //   setSelectContent([...aa])
        // }
      }
    }
  }
  //选中主企业，遍历循环找到主企业，并设置图标
  const IconMain = (treeSelect, treeDataList) => {
    const data = _.cloneDeep(treeDataList)
    data.forEach((item) => {
      item.children.map((it) => {
        if (it.key == treeSelect[0]) {
          it.icon = (
            <div
              style={{
                width: '15px',
                height: '15px',
                borderRadius: '10pX',
                backgroundColor: 'yellow',
                lineHeight: '15px'
              }}
            ></div>
          )
        } else {
          it.icon = <div></div>
        }
      })
    })
    setTreeDataList(data)
  }
  useEffect(() => {
    props.click(selectContent)
  }, [selectContent])
  const onExpand = (keys, info) => {
    // setExpandedKeys([info?.node.key])
    if (info.expanded == true) {
      setExpandedKeys([info?.node.key])
    } else {
      setExpandedKeys([])
    }
  }
  return (
    <div className="list-data">
      <Card
        title="企业列表"
        size="small"
        // style={{ height: '100%' }}
        bodyStyle={{ height: '90vh' }}
      >
        <div className="list-top-seacher">
          <Input
            placeholder="请输入搜索的公司名称"
            prefix={<SearchOutlined className="site-form-item-icon" />}
            onChange={onChange}
          />
        </div>
        <div className="list-taps">
          <div
            className={tap === '1' ? 'active' : 'list-area'}
            onClick={() => handleChange('1')}
          >
            地区
          </div>
          <div
            className={tap === '3' ? 'active' : 'list-hangye'}
            onClick={() => handleChange('3')}
          >
            行业
          </div>
        </div>
        <div className="list-bottom-data">
          {loading ? (
            <Spin tip="Loading......" style={{ height: '100%' }} />
          ) : (
            treeDataList.length > 0 &&
            treeDataList && (
              <DirectoryTree
                multiple={true}
                defaultExpandAll
                // defaultExpandedKeys={['0-0']} //默认展开指定的树节点
                // defaultSelectedKeys={defaultSelectedKeys} //默认选中的节点
                selectedKeys={selectedKeys} //（受控）设置选中的树节点
                expandedKeys={expandedKeys} //（受控）展开指定的树节点s
                onSelect={onSelect}
                onExpand={onExpand}
                treeData={treeDataList}
                autoExpandParent={autoExpandParent} //是否自动展开父节点
              />
            )
          )}
        </div>
      </Card>
    </div>
  )
}
export default List
